package cdu.sl.aichatdemo.service.impl;

import cdu.sl.aichatdemo.mapper.CustomChatMemoryMapper;
import cdu.sl.aichatdemo.pojo.entity.CustomChatMemory;
import cdu.sl.aichatdemo.service.TitleGenerateService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description 对话标题生成器
 * @Author sunlin5@asiainfo.com
 * @Date 2025/8/29
 * @Version 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TitleGenerateServiceImpl extends ServiceImpl<CustomChatMemoryMapper, CustomChatMemory> implements TitleGenerateService {

    private final ChatClient dashScopeChatClient;

    private final CustomChatMemoryMapper chatMemoryMapper;

    /**
     * 生成对话标题
     *
     * @param conversationId
     * @return
     */
    public String generateTitle(String conversationId) {
        // 准备参数
        List<CustomChatMemory> customChatMemories = chatMemoryMapper.selectByConversationId(conversationId);
        if (customChatMemories.size() < 2) {
            log.warn("对话内容太少,生成默认标题");
            return "新对话";
        }
        StringBuilder conversation = new StringBuilder();
        for (int i = 0; i < 2; i++) {
            conversation.append(customChatMemories.get(i).getType()).append(":").append(customChatMemories.get(i).getContent());
            conversation.append("\n");
        }
        String prompt = "请你根据对话的内容 , 为对话生成一个标题 , 不超过20个字, 要求简明扼要 , 能够体现核心内容,返回纯文字,不要带格式\n"
                + conversation;
        String content = dashScopeChatClient.prompt(prompt).call().content();
        // 批量更新
        LambdaUpdateWrapper<CustomChatMemory> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CustomChatMemory::getConversationId, conversationId);
        updateWrapper.set(CustomChatMemory::getTitle, content);
        update(updateWrapper);
        log.info("成功更新对话:{}标题为:{}", conversationId, content);
        return content;
    }


}
